<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { RequestPath, startRequest } from '../base/RequestWork';
import type { OrderData } from '../base/RequestWork';
import { ElMessage } from 'element-plus';

// 订单列表数据
let tableData = ref<OrderData[]>([])  // 添加类型注解
// 是否有更多数据
let hasMore = ref(true)
// 订单筛选条件
let filter = ref(-1)
// 分页数据
let limit = 4
// 存储订单状态与按钮类型的
let stateMap = [
    {
        title: "已付款，立即发货",
        type: "primary"
    },{
        title: "已发货",
        type: "success"
    },{
        title: "用户已收货",
        type: "success"
    },{
        title: "已完成",
        type: "success"
    }
]
// 存储筛选项
let options = [
    {
        title: "全部",
        value: -1
    },{
        title: "已付款",
        value: 0
    },{
        title: "已发货",
        value: 1
    },{
        title: "已收货",
        value: 2
    },{
        title: "已完成",
        value: 3
    }
]
let sort = ref("")
// 排序选项
let sorts = [
    {title: "默认排序", value: ""},
    {title: "按用户排序", value: "user_id"},
    {title: "按下单时间排序", value: "created_at"},
    {title: "按价格排序", value: "price"},
    {title: "按节省金额排序", value: "save_price"},
    {title: "按状态排序", value: "state"}
]
// 组件挂载时加载数据
onMounted(()=>{
    reLoadData()
})
// 刷新数据
function reLoadData() {
    tableData.value = []
    loadData()
}
// 加载数据
function loadData() {
    let params:any = {
        limit,
        offset: tableData.value.length,
        type: 0
    }
    if (filter.value >= 0) {
        params.filter = filter.value
    }
    if (sort.value.length > 0) {
        params.order = sort.value
    }
    
    console.log('开始请求订单数据，参数:', params);
    
    startRequest(RequestPath.orderListGet, 'get', params).then((response)=>{
        console.log('订单API响应:', response);
        
        // 修复：响应拦截器已经返回response.data，所以应该直接使用response.datas
        const responseData = response as any;
        const datas = responseData.datas ?? [];
        
        hasMore.value = datas.length >= limit;
        
        // 修复：更安全的类型转换
        if (Array.isArray(datas)) {
            tableData.value.push(...datas);
            console.log(`成功加载 ${datas.length} 条订单数据`);
        } else {
            console.error('返回的数据不是数组格式:', datas);
            ElMessage.error('返回数据格式错误');
        }
    }).catch((error)=>{
        console.error('加载订单数据失败:', error);
        ElMessage.error({
            message: error.response?.data?.error || '加载订单数据失败'
        })
    })
}

// 安全获取状态类型
function getStateType(state: number): string {
    const stateItem = stateMap[state];
    return stateItem?.type || 'info'; // 默认类型
}

// 安全获取状态标题
function getStateTitle(state: number): string {
    const stateItem = stateMap[state];
    return stateItem?.title || '未知状态';
}

// 对订单进行操作
function clickOrder(index: number) {
    // 修复类型转换错误：先检查是否存在，再安全转换
    const orderItem = tableData.value[index];
    if (!orderItem) {
        ElMessage.error({
            message: "订单不存在"
        });
        return;
    }
    
    // 使用更安全的类型转换方式
    let order = orderItem as unknown as OrderData;
    if (order.state == 0) {
        // 发货操作
        startRequest(RequestPath.orderUpdate, 'get', {
            oid: order.id,
            state: 1
        }).then(()=>{
            order.state = 1
            ElMessage.success({
                message: "发货成功"
            })
        }).catch((error)=>{
            ElMessage.error({
                message: error.response?.data?.error || '发货失败'
            })
        })
    }
}
</script>

<template>
    <div style="margin-top: 40px;margin-left: 20px; color: red;">我的订单</div>
    <!-- 筛选组件 -->
    <el-select v-model.number="filter" placeholder="筛选订单类型" size="large"
        style="width: 100px;margin: 20px; " @change="reLoadData">
        <el-option v-for="item in options" :key="item.value" :label="item.title" :value="item.value"/>
    </el-select>
    <!-- 排序组件 -->
    <el-select v-model="sort" placeholder="排序规则" size="large"
        style="width: 300px;margin: 20px; " @change="reLoadData">
        <el-option v-for="item in sorts" :key="item.value" :label="item.title" :value="item.value"/>
    </el-select>
    <!-- 订单列表 -->
    <div>
        <el-table :data="tableData" style="width: 100%">
            <el-table-column prop="id" label="订单编号" width="80" />
            <el-table-column prop="user_id" label="用户id" width="80" />
            <el-table-column label="商品信息"  width="280">
                <template #default="scope">
                    <!-- 修复：循环遍历加上key -->
                    <div v-for="(item, idx) in scope.row.goods" :key="idx" style="margin: 10px;">
                        <div>{{idx+1}}：{{ item.item.name }}  {{ item.count }}件</div>
                        <el-image style="width: 50px; height: 50px; margin: 5px;" :src="item.item.image" fit="fill" />
                        <div>单价：{{ item.item.discounted_price }}￥</div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="price" label="订单总价/￥" width="100" />
            <el-table-column prop="save_price" label="节省金额/￥" width="100" />
            <el-table-column prop="created_at" label="下单时间" width="200" />
            <el-table-column prop="address" label="收货地址" width="200" />
            <el-table-column label="操作"  width="180">
                <template #default="scope">
                    <!-- 修复：使用安全访问方法，避免stateMap[scope.row.state].type为undefined -->
                    <el-button 
                        :type="getStateType(scope.row.state)" 
                        @click="clickOrder(scope.$index)">
                        {{ getStateTitle(scope.row.state) }}
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <!-- 加载更多 -->
    <div v-show="hasMore" style="width: 100%; text-align: center; margin-top: 15px; color: grey;" @click="loadData">点击加载更多</div>
</template>